package com.copa.provider.music.kugou;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.copa.api.BaseRequest;
import com.copa.api.HttpEngine;
import com.copa.constant.Constants;
import com.copa.entity.Music;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.copa.constant.MusicType.KUGOU;

/**
 * @author copa
 * @createDate 2022-02-22 15:29
 * @function
 */
@SuppressWarnings("SpellCheckingInspection")
class KugouSearchMusicRequest extends BaseRequest<List<Music>> {
    private final String mKeyword;
    private static final int PAGE_SIZE = Constants.PAGE_SIZE;
    private final int mPage;
    private static final String SONG_URL_PREFIX = "https://www.kugou.com/song/#hash=";

    public KugouSearchMusicRequest(String keyword, int page) {
        mKeyword = keyword;
        mPage = page;
    }

    @Override
    protected Request buildRequest() {
        Request.Builder requestBuilder = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse("http://mobilecdn.kugou.com/api/v3/search/song").newBuilder();
        urlBuilder.addQueryParameter("keyword", mKeyword);
        urlBuilder.addQueryParameter("format", "json");
        urlBuilder.addQueryParameter("page", String.valueOf(mPage));
        urlBuilder.addQueryParameter("pagesize", String.valueOf(PAGE_SIZE));
        requestBuilder.url(urlBuilder.build());
        requestBuilder.addHeader(Constants.REFERER, "http://m.kugou.com/v2/static/html/search.html");
        requestBuilder.addHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) " +
                "AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
        requestBuilder.get();
        final Request request = requestBuilder.build();
        return request;
    }

    @Override
    protected List<Music> parseResult(Response response) throws IOException {
        String data = responseBodyToString(response);
        JSONObject responseJson = JSONObject.parseObject(data);
        JSONArray musicArray = responseJson.getJSONObject("data").getJSONArray("info");
        List<Music> musicList = new ArrayList<>();
        for (Object musicObj : musicArray) {
            JSONObject musicJsonObject = JSONObject.parseObject(musicObj.toString());
            Music music = Music.builder()
                    .title(musicJsonObject.getString("songname"))
//                    .musicUrl(SONG_URL_PREFIX + musicJsonObject.getString("hash")
//                            + "&album_id=" + musicJsonObject.getString("album_id"))
                    .brief(musicJsonObject.getString("topic"))
                    .jumpUrl(SONG_URL_PREFIX + musicJsonObject.getString("hash")
                            + "&album_id=" + musicJsonObject.getString("album_id"))
                    .type(KUGOU.getAlias())
                    //.pictureUrl(musicJsonObject.getJSONObject("al").getString("picUrl"))
                    .summary(musicJsonObject.getString("singername"))
                    .build();
            addMusicUrlAndImg(music, musicJsonObject.getString("hash"), musicJsonObject.getString("album_id"));
            musicList.add(music);
            break;
        }

        return musicList;
    }

    private Music addMusicUrlAndImg(Music music, String hash, String albumId) {
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url("https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery19107465224671418371_1555932632517&" +
                "hash=" + hash +"&album_id=" + albumId);
        requestBuilder.addHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) " +
                "AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
        requestBuilder.addHeader("cookie", "kg_mid=1");
        Request build = requestBuilder.get().build();
        try {
            Response response = HttpEngine.requestSync(build, useProxy());
            String data = responseBodyToString(response);
            data = data.replace("jQuery19107465224671418371_1555932632517(", "")
                    .replace(");", "");
            JSONObject musicDetailJsonObject = JSONObject.parseObject(data).getJSONObject("data");
            music.setMusicUrl(musicDetailJsonObject.getString("play_backup_url"))
                    .setPictureUrl(musicDetailJsonObject.getString("img"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return music;
    }
}
